package com.semeureka.frame.util;

import java.beans.PropertyEditorSupport;
import java.net.InetSocketAddress;

import org.apache.mina.transport.serial.SerialAddress;
import org.apache.mina.transport.serial.SerialAddress.DataBits;
import org.apache.mina.transport.serial.SerialAddress.FlowControl;
import org.apache.mina.transport.serial.SerialAddress.Parity;
import org.apache.mina.transport.serial.SerialAddress.StopBits;

public class SocketAddressPropertyEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text.matches("\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+")) {
			String hostname = text.substring(0, text.indexOf(":"));
			int port = Integer.parseInt(text.substring(text.indexOf(":") + 1));
			setValue(new InetSocketAddress(hostname, port));
		} else if (text.matches("COM\\d+:\\d+")) {
			String name = text.substring(0, text.indexOf(":"));
			int bauds = Integer.parseInt(text.substring(text.indexOf(":") + 1));
			setValue(new SerialAddress(name, bauds, DataBits.DATABITS_8, StopBits.BITS_1, Parity.NONE, FlowControl.NONE));
		} else {
			throw new IllegalArgumentException(text);
		}
	}
}
